package com.auxgroup.hr.front.site.co.process;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.validation.Valid;

import com.alibaba.fastjson.JSONObject;
import com.auxgroup.hr.front.commons.enums.WfTypeEnum;
import com.auxgroup.hr.front.dao.domain.*;
import com.auxgroup.hr.front.site.co.BaseWfCO;
import com.auxgroup.hr.front.site.inteceptor.SessionGain;
import com.auxgroup.hr.front.site.vo.process.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.auxgroup.hr.front.commons.BaseRetCode;
import com.auxgroup.hr.front.commons.vo.BaseResponseVO;
import com.auxgroup.hr.front.commons.vo.UserDTO;
import com.auxgroup.hr.front.dozer.IObjectMapper;
import com.auxgroup.hr.front.service.personnal.PersonalDataService;
import com.auxgroup.hr.front.service.process.ProcessService;
import com.auxgroup.hr.front.service.process.WfFileService;
import com.auxgroup.hr.front.site.co.BaseCO;
import com.auxgroup.hr.front.site.vo.process.ProcessApplyFrom;
import com.auxgroup.hr.front.site.vo.process.WfCataLogRespVO;
import com.auxgroup.hr.front.site.vo.process.WfFileReqVO;
import com.auxgroup.hr.front.site.vo.process.WfStatusReqVO;
import com.auxgroup.hr.front.site.vo.process.WfStatusRespVO;
import com.auxgroup.hr.front.ws.ProcessApplyQueDTO;
import com.auxgroup.hr.front.ws.ProcessApproveQueDTO;

/**
 * 流程审批CO
 * 
 * @author wangchangyun
 * @version 创建时间：180527
 */
@RestController
@RequestMapping("${auxgroup.hr.contextPath}/process")
public class ProcessCO extends BaseWfCO {

	private static final Logger logger = LoggerFactory.getLogger(ProcessCO.class);

	@Autowired
	public ProcessService  processService;
	
	@Autowired
	private WfFileService wfFileService;
	
	@Autowired
	public PersonalDataService personalDataService;
	
	@Resource(name = "dozerMapper")
	protected IObjectMapper objectMapper;

//	@GetMapping(value="/isproposer")
//	public BaseResponseVO isProposer(String transNum, @SessionGain("user") UserDTO user){
//
//		return buildRespone(transNum);
//	}
	
	/**
	 * 流程审批
	 * @param approveFrom
	 * @return
	 */
	@PostMapping(value="/approve")
	public BaseResponseVO approve(@Valid BaseApproveReq approveFrom, BindingResult binding, @SessionGain("user") UserDTO user){
		logger.info("process approve param:{}",approveFrom);
		// 表单校验
        super.assertValidation(binding);

        //审批流程
		return requestWs(approveFrom.getcWfType(), approveFrom, user);
	}
	
	
	/**
	 * 获取流程编号
	 * @return
	 */
	@GetMapping("/getTransNum")
	public BaseResponseVO getTransNum(){
		String transNum = processService.getTranNum();
		if(StringUtils.isBlank(transNum)){
			return buildRespone(BaseRetCode.CODE_ERROR_PROCESS_GET_TRANSNUM_FAIL);
		}
		return buildRespone(transNum);
	}
	
	/**
	 * 流程申请
	 * @param applyFrom
	 * @param binding
	 * @return
	 */
	@PostMapping("/apply")
	public BaseResponseVO apply(@Valid ProcessApplyFrom applyFrom, BindingResult binding, @SessionGain("user") UserDTO user){
		logger.info("process apply param:{}",applyFrom);
		// 表单校验
        super.assertValidation(binding);
        applyFrom.setC_USERID(user.getOprId());
		ProcessApplyQueDTO requestDTO = objectMapper.map(applyFrom, ProcessApplyQueDTO.class);
		Map<String, String> resp = processService.apply(requestDTO);
		if(resp==null||resp.isEmpty()){
			return buildRespone(BaseRetCode.CODE_ERROR_PROCESS_APRROVE_FAIL);
		}
        if("0".equals(resp.get("C_MSG_CODE"))){
        	return buildRespone(BaseRetCode.CODE_SUCCESS);
        }else{
        	return buildRespone(resp.get("C_MSG_CODE"), resp.get("C_MSG_TEXT"));
        }
	}
	
	/**
	 * 获取流程审批人列表
	 * @param transNum
	 * @return
	 */
	@GetMapping(value="/processMap")
	public BaseResponseVO processMap(String transNum){
		logger.info("process processMap param:{}",transNum);
		List<List<ProcessMapRespVO>> respVOs = processService.processMap(transNum);
		return buildRespone(respVOs,false);
	}


	/**
	 * 获取流程已处理节点
	 * @param transNum
	 * @return
	 */
	@GetMapping(value="/processedNode")
	public BaseResponseVO processedNode(String transNum){
		logger.info("process processedNode param:{}",transNum);
		List<ProcessMapRespVO> respVOs = processService.processedNode(transNum);
		return buildRespone(respVOs,false);
	}
	
	
	
	/**
	 * 待办事项列表
	 * @return
	 */
	@GetMapping(value="/getTODOlist")
	public BaseResponseVO getTODOlist(WfStatusReqVO reqVO, @SessionGain("user") UserDTO user){
		logger.info("process getTODOlist param:{}",reqVO);
		reqVO.setOprid(user.getOprId());
		PsCWfStatusVw wfStatus = objectMapper.map(reqVO, PsCWfStatusVw.class);
		wfStatus.setText254(reqVO.getQueryKey());
		List<PsCWfStatusVw> wfList = processService.getTODOlist(wfStatus);
		List<WfStatusRespVO> respVOs = (List<WfStatusRespVO>)objectMapper.map(wfList,WfStatusRespVO.class,List.class);
//		respVOs.forEach(r -> {
//			r.setText254(sysDictService.getWfTitle(r.getcTransactionNbr()));
//		});
		return buildRespone(respVOs,false);
	}
	
	
	/**
	 * 待办事项个数
	 * @return
	 */
	@GetMapping(value="/getTODONums")
	public BaseResponseVO getTODONums(WfStatusReqVO reqVO,@SessionGain("user") UserDTO user){
		logger.info("process getTODONums param:{}",reqVO);
		reqVO.setOprid(user.getOprId());
//		if(StringUtils.isBlank(reqVO.getcUserStatus())){
//			reqVO.setcUserStatus("P");//默认查待审批的
//		}
		PsCWfStatusVw wfStatus = objectMapper.map(reqVO, PsCWfStatusVw.class);
		List<PsCWfStatusVw> wfList = processService.getTODOlist(wfStatus);
		return buildRespone(wfList==null?0:wfList.size(),false);
	}
	
	
	/**
	 * 已审批事项列表
	 * @return
	 */
	@GetMapping(value="/getApprovedlist")
	public BaseResponseVO getApprovedlist(WfStatusReqVO reqVO,@SessionGain("user") UserDTO user){
		logger.info("process getApprovedlist param:{}",reqVO);
		reqVO.setOprid(user.getOprId());
		PsCWfStatusVw wfStatus = objectMapper.map(reqVO, PsCWfStatusVw.class);
		wfStatus.setText254(reqVO.getQueryKey());
		List<PsCWfStatusVw> wfList = processService.getApprovedlist(wfStatus);
		List<WfStatusRespVO> respVOs = (List<WfStatusRespVO>)objectMapper.map(wfList,WfStatusRespVO.class,List.class);
		return buildRespone(respVOs,false);
	}
	
	
	/**
	 * 我的申请列表
	 * @param user
	 * @return
	 */
	@GetMapping(value="/getMyApply")
	public BaseResponseVO getMyCreatedProcess(WfStatusReqVO reqVO,@SessionGain("user") UserDTO user){
		logger.info("process getMyApply param:{}",reqVO);
		PsCWfCatalog queryCata = new PsCWfCatalog();
		queryCata.setCreatedBy(user.getOprId());
		queryCata.setText254(reqVO.getQueryKey());
		List<PsCWfCatalog> catas = processService.getMyCreatedProcess(queryCata);
		List<WfCataLogRespVO> respVOs = (List<WfCataLogRespVO>)objectMapper.map(catas,WfCataLogRespVO.class,List.class);
		return buildRespone(respVOs,false);
	}
	
	/**
	 * 上传流程附件
	 * @return
	 */
	@PostMapping(value="/uploadWfFile")
	public BaseResponseVO uploadWfFile(@RequestParam("fileName") String base64,WfFileReqVO reqVo, @SessionGain("user") UserDTO user){
		if(StringUtils.isBlank(reqVo.getWfType())){
			return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL.getRetCode(),"流程类型不能为空");
		}
		String transNum;
		if(StringUtils.isBlank(reqVo.getcTransactionNbr())){
			transNum = processService.getTranNum();
		}else{
			transNum = reqVo.getcTransactionNbr();
		}
		PsCModAttTPrimary primary = new PsCModAttTPrimary();
		primary.setcTransactionNbr(transNum);
		//如果编号没有传，就说明是创建流程时上传的附件
		if(reqVo.getcStepNbr()==null){
			primary.setcStepNbr(new BigDecimal(0));
		}else{
			primary.setcStepNbr(reqVo.getcStepNbr());
		}
		if(reqVo.getcUserNbr()==null){
			primary.setcUserNbr(new BigDecimal(0));
		}else{
			primary.setcUserNbr(reqVo.getcUserNbr());
		}
		PsCModAttT fileAtt = wfFileService.uploadWfFile(base64, user, primary, reqVo.getWfType(),reqVo.getOriginName());
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("cTransactionNbr", fileAtt.getcTransactionNbr());
		resultMap.put("seqnbr", fileAtt.getSeqnbr());
		resultMap.put("fileitem", fileAtt);
		return buildRespone(resultMap,false);
	}
	
	
	
	
	/**
	 * 上传流程附件
	 * @return
	 */
	@PostMapping(value="/delWfFile")
	public BaseResponseVO delWfFile(String cTransactionNbr,String seqnbr ){
		logger.info("delwfFile param transNum:{},seqNbr:{}",cTransactionNbr,seqnbr);
		if(StringUtils.isBlank(seqnbr)){
			return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL.getRetCode(),"文件序号不能为空");
		}
		if(StringUtils.isBlank(cTransactionNbr)){
			return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL.getRetCode(),"流程编号不能为空");
		}
		wfFileService.delWfFile(cTransactionNbr, seqnbr);
		return buildRespone(BaseRetCode.CODE_SUCCESS);
	}


	@Override
	protected Set<String> getAuthFileds() {
		return null;
	}
}
